﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using EIS.Obj;
using EIS.ServerAdapter;
using Ext.Connector.EIS;

namespace EIS.ConnectorFactory
{
    public class ConnectorFactory
    {
        public ConnectorMeta GetConnector(string functionID)
        {
            string url = GlobalVariable.Instance.ServerRootURL;

            url = url + @"functionDestInvokeInfo/" + functionID + @"/" + GlobalVariable.Instance.CurrentToken + ".xml";

            DataSet dsInvokeInfo = RestAdapter.HttpGet(url);

            if (dsInvokeInfo.Tables.Count == 0) return null;
            if  ( dsInvokeInfo.Tables[0].TableName.ToUpper() == "ERROR")
            {
                throw new Exception(dsInvokeInfo.Tables[0].Rows[0]["errorCode"].ToString() + dsInvokeInfo.Tables[0].Rows[0]["errorMessage"].ToString() );
            }
            var dr = dsInvokeInfo.Tables[0].Rows[0];

            string strBaseDir = AppDomain.CurrentDomain.BaseDirectory;
            string strPathToAsm = Path.Combine(strBaseDir, dr["connectorLibraryFileName"].ToString());
            try
            {
                Assembly objAsm = Assembly.LoadFile(strPathToAsm);
                object[] args = new string[]{functionID};
                Type type = objAsm.GetType(dr["connectorClassName"].ToString());
                
                object instance = Activator.CreateInstance(type, args);

                MethodInfo method = type.GetMethod("Execute");

                return new ConnectorMeta(method, instance);
            }
            catch (Exception objException)
            {
                //TODO
                return null;
            }
        }
    }
}
